/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.fedoraaccess.rest;

import cz.mzk.kramerius.fedoraaccess.FedoraServer;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
class AddRelationshipOperation extends AbstractOperation {

    private static final String RDF_PID_PREFIX = "info:fedora/";
    public static final Logger logger = Logger.getLogger(AddRelationshipOperation.class.getName());

    public AddRelationshipOperation(FedoraServer fedoraServer) {
        super(new HttpConnector(fedoraServer, HttpMethod.POST));
    }

    public String run(String subjectPid, String predicate, String objectPid) {
        String request = buildRequest(subjectPid, predicate, objectPid);
        logger.log(Level.FINE, "request: ''{0}''", request);
        try {
            return connector.processRequestWithStringResult(request);
        } catch (IOException ex) {
            logger.log(Level.SEVERE, "error adding relationship. AddRelationship is supported in REST API from Fedora 3.4 ", ex);
            return null;
        }
    }

    private String buildRequest(String subjectPid, String predicate, String objectPid) {
        StringBuilder builder = new StringBuilder();
        builder.append(getBaseUrl());
        builder.append("/objects/").append(subjectPid);
        builder.append("/relationships/new?");
        String subject = encodeAttribute(RDF_PID_PREFIX.concat(subjectPid));
        builder.append("subject=").append(subject);
        builder.append("&predicate=");
        builder.append(encodeAttribute(predicate));
        builder.append("&object=");
        builder.append(encodeAttribute(objectPid));
        builder.append("&isLiteral=true");
        return builder.toString();
    }
}
